import java.util.ArrayList;
import java.util.List;

//leetcode 22 括号生成
public class Test1 {
    List<String> ret;
    StringBuilder path;
    int left, right, n;
    public List<String> generateParenthesis(int _n) {
        ret = new ArrayList<>();
        path = new StringBuilder();
        n = _n;
        dfs();
        return ret;
    }

    private void dfs() {
        if (right == n) {
            ret.add(path.toString());
            return;
        }
        if (left < n) {
            path.append("("); left++;
            dfs();
            path.deleteCharAt(path.length() - 1); left--;
        }
        if (right < left) {
            path.append(")"); right++;
            dfs();
            path.deleteCharAt(path.length() - 1); right--;
        }
    }
}
